﻿using System;
using System.Linq;
using System.Collections.ObjectModel;
using System.Text;

namespace PengSW.Script
{
    public static class TriggerScriptManager
    {
        public static void OnTrigger(string aKey, object aParameter)
        {
            StringBuilder aExceptionMessages = new StringBuilder();
            foreach(var aTriggerScript in from r in TriggerScripts where r.Key == aKey select r)
            {
                try
                {
                    aTriggerScript?.Action?.Exec(aParameter);
                }
                catch (Exception ex)
                {
                    aExceptionMessages.AppendLine(ex.Message);
                }
            }
            if (aExceptionMessages.Length > 0) throw new ApplicationException(aExceptionMessages.ToString());
        }

        public static void RegisterTrigger(string aKey, string aScript)
        {
            TriggerScript aTriggerScript = new TriggerScript
            {
                Key = aKey,
                Script = aScript,
            };
            aTriggerScript.Compile();
            TriggerScripts.Add(aTriggerScript);
        }

        public static ObservableCollection<TriggerScript> TriggerScripts { get; } = new ObservableCollection<TriggerScript>();
    }
}
